<?php
class CommonAction extends Action
{

    protected $id; //每个控制器里，当前操作的主PK值

    protected $curModel = null; //当前控制器专用模型

    protected $uid = 0;
    protected $username = "";

    /**
     * 如果是分店登录，则必须有此id
     * @var int
     */
    protected $bossID = 0;

    public function _initialize()
    {
        if ( isset( $_POST['PHPSESSID'] ) ) {
            session_write_close();
            session_id( $_POST[session_name()] );
            session_start();
        }

        $this->curModel = D( MODULE_NAME );

        // 用户权限检查
        if ( C( 'USER_AUTH_ON' ) && !in_array( MODULE_NAME , explode( ',' , C( 'NOT_AUTH_MODULE' ) ) ) ) {
            import( '@.ORG.Util.RBAC' );
            //            if (!RBAC::AccessDecision()) {
            //检查认证识别号
            if ( !$_SESSION [ C( 'USER_AUTH_KEY' ) ] ) {
                //跳转到认证网关
                redirect( PHP_FILE . C( 'USER_AUTH_GATEWAY' ) );
            }
            // 没有权限 抛出错误
            if ( C( 'GUEST_AUTH_ON' ) ) {
                $this->assign( 'jumpUrl' , PHP_FILE . C( 'USER_AUTH_GATEWAY' ) );

                // 提示错误信息
                $this->error( L( '_VALID_ACCESS_' ) );
            }
            //            }
        }

        $this->id = $this->_request( $this->curModel->getPk() ) > 0 ? $this->_request( $this->curModel->getPk() ) : 0;

        $this->logO = D( 'AdminLog' );
        $this->uid = $_SESSION[C( 'USER_AUTH_KEY' )];
        $this->username = $_SESSION['USER_AUTH_NAME'];
        $_SESSION['loginBossID'] > 0 && $this->bossID = $_SESSION['loginBossID'];

        //订单自动成功
        import('@.ORG.Util.OrderSuccess');
        OrderSuccess::run();

        $this->actionLogSave();
    }

    /**
     * 动作日志自动保存
     */
    protected function actionLogSave()
    {
        // $this->logO->addLog( ($_SERVER['REQUEST_METHOD'] == 'POST' ? "提交:" : "访问:" ). ($_SERVER['PATH_INFO'] == "" ? $_SERVER['REDIRECT_URL'] : $_SERVER['PATH_INFO']), serialize( $_REQUEST ) );
    }

    protected function getWebOptions()
    {
        $webOptionsO = D( 'Options' );
        $this->webOptions = $webOptionsO->getAllOptions();
    }


    //注销
    public function logout()
    {
        session( null );
        $this->success( "成功退出后台。" );
    }

    /*
    * 自动生产查询条件
    * 并且将搜索项assign模板
    * @param 表名
    * return array
    */
    protected function _search( $name = '' )
    {
        $map = array();
        foreach ( $this->curModel->getDbFields() as $key => $val ) {
            if ( isset( $_REQUEST[$val] ) && $_REQUEST [$val] != '' ) {
                $map[$val] = trim( $_REQUEST [$val] );
            }
        }

        $this->assign( 'params', $map );

        return $map;
    }


    /*
    * 分页方法,配合dwz呈现分页样式
    * 并不需要再去计算复杂的分页层级、列表，这一切由dwz实现
    * php只需要提供：总数、每页显示数、当前页数即可
    * @param 总记录数
    * @param 一页显示数量
    * return obj
    */
    protected function _page( $count = 0, $num = 0, $isDialog = false )
    {
        import( '@.ORG.Util.HPage' );

        if ( $count == 0 && $num == 0 ) $page = new HPage( $this->curModel->count(), C( 'PAGE_LIMIT' ), $this->view, $isDialog ); else
            $page = new HPage( $count, $num == 0 ? C( 'PAGE_LIMIT' ) : $num, $this->view, $isDialog );

        return $page;
    }

    /**
     * 提高PHP上传图片的处理能力
     */
    protected function _ChangeIniForuploadFile()
    {
        ini_set( 'max_execution_time', 300 ); //5分钟才算超时
        ini_set( 'max_input_time', 300 ); //接受GET OR POST数据的超时时间是5分钟
        //        ini_set('post_max_size','12M');  //5分钟才算超时
    }

    /**
     *清空所有临时图片
     * 其实这里我很想写成php5.4才有的内部函数，配合递归，But，我还是这样写吧=w=
     */
    public function clearImageTempFile(){
        $dir = $_SERVER['DOCUMENT_ROOT'].DS.C('UPLOAD_IMAGE_TEMP_DIR');
        if(file_exists($dir)){
            $dh = opendir($dir);
            while (($file = readdir($dh)) !== false) {
                if($file == '..' || $file == '.') continue;
                if(!is_file($file)){
                    $tempDirH = opendir($dir.DS.$file);
                    while (($deepFile = readdir($tempDirH)) !== false) {
                        if($deepFile == '..' || $deepFile == '.') continue;
                        unlink($dir.DS.$file.DS.$deepFile);
                    }
                    rmdir($dir.DS.$file);
                    unset($tempDirH);
                }else{
                    dump(unlink($dir.DS.$file));
                }
            }
        }
    }

    public function index(){
        //列表过滤器，生成查询Map对象
        $map = $this->_search();
        if (method_exists($this, '_filter')) {
            $this->_filter($map);
        }
        $name = $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            $this->_list($model, $map);
        }
        $this->display();
        return;
    }

    /**
    +----------------------------------------------------------
     * 取得操作成功后要返回的URL地址
     * 默认返回当前模块的默认操作
     * 可以在action控制器中重载
    +----------------------------------------------------------
     * @access public
    +----------------------------------------------------------
     * @return string
    +----------------------------------------------------------
     * @throws ThinkExecption
    +----------------------------------------------------------
     */
    function getReturnUrl() {
        return __URL__ . '?' . C('VAR_MODULE') . '=' . MODULE_NAME . '&' . C('VAR_ACTION') . '=' . C('DEFAULT_ACTION');
    }

    /**
    +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
    +----------------------------------------------------------
     * @access protected
    +----------------------------------------------------------
     * @param Model $model 数据对象
     * @param HashMap $map 过滤条件
     * @param string $sortBy 排序
     * @param boolean $asc 是否正序
    +----------------------------------------------------------
     * @return void
    +----------------------------------------------------------
     * @throws ThinkExecption
    +----------------------------------------------------------
     */
    protected function _list($model, $map, $sortBy = '', $asc = false) {
        //排序字段 默认为主键名
        if (isset($_REQUEST ['_order'])) {
            $order = $_REQUEST ['_order'];
        } else {
            $order = !empty($sortBy) ? $sortBy : $model->getPk();
        }
        //排序方式默认按照倒序排列
        //接受 sost参数 0 表示倒序 非0都 表示正序
        if (isset($_REQUEST ['_sort'])) {
            $sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
        } else {
            $sort = $asc ? 'asc' : 'desc';
        }
        //取得满足条件的记录数
        $count = $model->where($map)->count('id');
        if ($count > 0) {
            //创建分页对象
            if (!empty($_REQUEST ['listRows'])) {
                $listRows = $_REQUEST ['listRows'];
            } else {
                $listRows = '';
            }
            $p = $this->_page($count,$listRows);
            //分页查询数据

            $voList = $model->where($map)->order("`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
            //echo $model->getlastsql();
            //分页跳转的时候保证查询条件
            foreach ($map as $key => $val) {
                if (!is_array($val)) {
                    $p->parameter .= "$key=" . urlencode($val) . "&";
                }
            }
            //分页显示
            $page = $p->show();
            //列表排序显示
            $sortImg = $sort; //排序图标
            $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
            $sort = $sort == 'desc' ? 1 : 0; //排序方式
            //模板赋值显示
            $this->assign('list', $voList);
            $this->assign('sort', $sort);
            $this->assign('order', $order);
            $this->assign('sortImg', $sortImg);
            $this->assign('sortType', $sortAlt);
            $this->assign("page", $page);
        }
        cookie('_currentUrl_', __SELF__);
        return;
    }

    function insert() {
        $name = $this->getActionName();
        $model = D($name);
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        //保存当前数据对象
        $list = $model->add();
        if ($list !== false) { //保存成功
            $this->success('新增成功!',cookie('_currentUrl_'));
        } else {
            //失败提示
            $this->error('新增失败!');
        }
    }

    function add(){
        $this->display();
    }

    function read() {
        $this->edit();
    }

    function edit() {
        $name = $this->getActionName();
        $model = M($name);
        $id = $_REQUEST [$model->getPk()];
        $vo = $model->getById($id);
        $this->assign('one', $vo);
        $this->display('add');
    }

    function update() {
        $name = $this->getActionName();
        $model = D($name);
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        // 更新数据
        $list = $model->save();
        if (false !== $list) {
            //成功提示
            $this->success('编辑成功!',cookie('_currentUrl_'));
        } else {
            //错误提示
            $this->error('编辑失败!');
        }
    }

    /**
    +----------------------------------------------------------
     * 默认删除操作
     * 当表结构中存在status时，将内容状态设置为禁用（status = 0 ）
     * 当表结构中不存在status时，则彻底删除这条记录
    +----------------------------------------------------------
     * @access public
    +----------------------------------------------------------
     * @return string
    +----------------------------------------------------------
     * @throws ThinkExecption
    +----------------------------------------------------------
     */
    public function delete() {
        //删除指定记录
        if (!empty($this->curModel)) {
            $pk = $this->curModel->getPk();
            $id = $_REQUEST [$pk];
            if (isset($id)) {
                $condition = array($pk => array('in', explode(',', $id)));
                if ((in_array('status', $this->curModel->getDbFields()))) {
                    $result = $this->curModel->where($condition)->setField('status', -1);
                } else {
                    $result = $this->curModel->where($condition)->delete();
                }
                if ($result !== false) {
                    $this->success('删除成功！');
                } else {
                    $this->error('删除失败！');
                }
            } else {
                $this->error('非法操作');
            }
        }
    }

    public function foreverdelete() {
        //删除指定记录
        $name = $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            $pk = $model->getPk();
            $id = $_REQUEST [$pk];
            if (isset($id)) {
                $condition = array($pk => array('in', explode(',', $id)));
                if (false !== $model->where($condition)->delete()) {
                    $this->success('删除成功！');
                } else {
                    $this->error('删除失败！');
                }
            } else {
                $this->error('非法操作');
            }
        }
        $this->forward();
    }

    public function clear() {
        //删除指定记录
        $name = $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            if (false !== $model->where('status=1')->delete()) {
                $this->success(L('_DELETE_SUCCESS_'),$this->getReturnUrl());
            } else {
                $this->error(L('_DELETE_FAIL_'));
            }
        }
        $this->forward();
    }

    /**
    +----------------------------------------------------------
     * 默认禁用操作
     *
    +----------------------------------------------------------
     * @access public
    +----------------------------------------------------------
     * @return string
    +----------------------------------------------------------
     * @throws FcsException
    +----------------------------------------------------------
     */
    public function forbid() {
        $name = $this->getActionName();
        $model = D($name);
        $pk = $model->getPk();
        $id = $_REQUEST [$pk];
        $condition = array($pk => array('in', $id));
        $list = $model->forbid($condition);
        if ($list !== false) {
            $this->success('状态禁用成功',$this->getReturnUrl());
        } else {
            $this->error('状态禁用失败！');
        }
    }

    public function recycle() {
        $name = $this->getActionName();
        $model = D($name);
        $pk = $model->getPk();
        $id = $_GET [$pk];
        $condition = array($pk => array('in', $id));
        if (false !== $model->recycle($condition)) {
            $this->success('状态还原成功！',$this->getReturnUrl());
        } else {
            $this->error('状态还原失败！');
        }
    }

    public function recycleBin() {
        $map = $this->_search();
        $map ['status'] = - 1;
        $name = $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            $this->_list($model, $map);
        }
        $this->display();
    }

    /**
    +----------------------------------------------------------
     * 默认恢复操作
     *
    +----------------------------------------------------------
     * @access public
    +----------------------------------------------------------
     * @return string
    +----------------------------------------------------------
     * @throws FcsException
    +----------------------------------------------------------
     */
    function resume() {
        //恢复指定记录
        $pk = $this->curModel->getPk();
        $id = $_GET [$pk];
        $condition = array($pk => array('in', $id));
        if (false !== $this->curModel->resume($condition)) {
            $this->success('状态恢复成功！',$this->getReturnUrl());
        } else {
            $this->error('状态恢复失败！');
        }
    }

    /**
     * 常规上传
     * 一般搭配kindeditor
     * @TODO：并未做严格检测，只检测了扩展名
     * @return void
     * @author
     **/
    public function kindeditor_upload()
    {
        $this->_ChangeIniForuploadFile();
        $allowEx = array("jpeg","jpg","gif","png","pjpg");
        // dump($_FILES);
        $tmpFile = $_FILES['imgFile']['tmp_name'];
        $size = $_FILES['imgFile']['size'];
        $ext = substr($_FILES['imgFile']['name'],-3);
        $maxSize = 1550000; //差不多1.5M
        $dir = $_SERVER['DOCUMENT_ROOT'].DS.$returnDir = C('UPLOAD_IMAGE_DIR').date('Y-m-d').DS;

        if($_FILES['imgFile']['error'] > 0 )    die(json_encode(array("error"=>1,"message"=>"上传失败")));

        // if(function_exists('exif_imagetype')){
        //     $ext = exif_imagetype($tmpFile);
        // }else{
        //     $info = pathinfo($_FILES['imgFile']['name']);
        //     $ext = $info['extension'];
        // }

        if(empty($ext) || !in_array(strtolower($ext),$allowEx))   die(json_encode(array("error"=>1,"message"=>"格式不对，请上传图片格式")));

        if($size > $maxSize)  die(json_encode(array("error"=>1,"message"=>"文件超出大小，请上传1.4m以下的图片")));

        if(!file_exists($dir)){
            if(false === mkdir($dir,0755)) die(json_encode(array("error"=>1,"message"=>"创建保存目录".$dir."失败")));
        }

        $filename = md5($tmpFile).".".$ext;

        if(false === copy($tmpFile,$dir.$filename)) die(json_encode(array("error"=>1,"message"=>"文件保存失败！")));

        die(json_encode(array("error"=>0,"url"=>$returnDir.$filename)));

    }

    /**
     * 通用上传文件接口
     * 不适用于ajax
     *
     * @paremt $name
     * @return bool
     */
    public function normal_upload($name){

        $this->_ChangeIniForuploadFile();
        $allowEx = array("jpeg","jpg","gif","png","pjpg");
        $tmpFile = $_FILES[$name]['tmp_name'];
        $size = $_FILES[$name]['size'];
        $ext = substr($_FILES[$name]['name'],-3);
        $maxSize = 1550000; //差不多1.5M
//        $dir =  realpath('.').DS.$returnDir = C('UPLOAD_IMAGE_DIR').date('Y-m-d').DS;
        $dir =  realpath('.').DS.$returnDir = C('UPLOAD_IMAGE_DIR');

        if($_FILES[$name]['error'] > 0 )    return false;

        if(empty($ext) || !in_array(strtolower($ext),$allowEx))   return "请上传正确的格式！";

        if($size > $maxSize)  return "图片超出了限制！";

        if(!file_exists($dir)){
            if(false === mkdir($dir,0755)) return "目录创建失败！".$dir;
        }

        $filename = md5($tmpFile).".".$ext;

        if(false === copy($tmpFile,$dir.$filename)) return "权限不足，文件保存失败！".$dir.$filename;

        return $returnDir.$filename;
    }


}